package com.youhome.service.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.ResultCode;
import com.youhome.common.response.ResultPage;
import com.youhome.service.mapper.NewsMapper;
import com.youhome.service.model.News;

import com.youhome.service.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by chen365 on 2019/01/23.
 */
@Service
@Slf4j
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsMapper newsMapper;

    @Override
    public News selectByPrimaryKey(Long id) throws CustomException {
        News news = newsMapper.selectByPrimaryKey(id);
        if (news == null) {
            throw new CustomException(ResultCode.NO_DATA_EXIST);
        }
        return news;
    }

    @Override
    public PageInfo<News> selectByBean(Integer pageNumber, Integer pageSize, News record) {
        if (StringUtils.isEmpty(pageNumber) || pageNumber < 1) {
            pageNumber = 1;
        }
        if (StringUtils.isEmpty(pageSize) || pageSize < 1) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNumber, pageSize);
        List<News> list = newsMapper.selectByBean(record);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<News> selectByType(Integer type, Integer pageNumber, Integer pageSize) throws CustomException {

        News record = new News();
        if (type != null && type > 0) {
            record.setType(type);
        }
        record.setStatus(1);

        if (StringUtils.isEmpty(pageNumber) || pageNumber < 1)
            pageNumber = 1;
        if (StringUtils.isEmpty(pageSize) || pageSize < 1)
            pageSize = 10;
        PageHelper.startPage(pageNumber, pageSize);

        List<News> list = newsMapper.selectByBean(record);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<News> selectTop10() throws CustomException {
        News record = new News();
        record.setIstop(1);
        record.setStatus(1);

        PageHelper.startPage(1, 10);
        List<News> list = newsMapper.selectByBean(record);
        return new PageInfo<>(list);

    }
}
